import axios from "axios"
import { DialogPlugin } from "tdesign-vue-next"
import { goPath } from "@/utils/goPath"
// Create axios instance
const baseURL = import.meta.env["VITE_API_URL"]
const instance = axios.create({
  baseURL,
  timeout: 5000,
  withCredentials: true // Carrying cookie
})
// Request interceptor
instance.interceptors.request.use(
  (config) => {
    // What can be done before the request is sent
    config.headers.Authorization = "MaoJiuYuQi"
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor
instance.interceptors.response.use(
  (response) => {
    // What can be done after receiving response data
    if(response.data.code && response.data.code === "expire"){
        const confirmDia = DialogPlugin({
          header: "温馨提示",
          body: "登录已过期，请重新登录~",
          onConfirm: () => {
            confirmDia.hide()
            goPath("/login/admin")

          },
          onClose: () => {
            confirmDia.hide()
          },
        })
    }
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)
// GET request
export const get = (url: string): any => {
 return instance.get(url)
}
// POST request
export const post = (url: string, data = {}): any => {
  return instance.post(url, data)
}
// API URL
export const apiUrl = (url = ""): string => {
  if (url[0] !== "/") {
    url = "/" + url
  }
  return baseURL + url
}

export default instance
